<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Throwable;
use Modules\Common\Exceptions\ApiException;
class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {

        });
    }
    public function render($request,Throwable $e)
    {

        if($request->is("api/*")){

            // api接口主动抛出的异常
            if ($e instanceof ApiException) {
                $result = [
                    "status"=>0,
                    "code"=>$e->getCode(),
                    "message"=>$e->getMessage()
                ];
                if(isset($e->getTrace()[0]['args'][0]['data'])){
                    $result['data'] = $e->getTrace()[0]['args'][0]['data'];
                }
                return response()->json($result,400);
                //如果错误是 ValidationException的一个实例，说明是一个验证的错误
            }else if($e instanceof ValidationException){
                $result = [
                    "status"=>0,
                    "code"=>400,
                    "message"=>array_values($e->errors())[0][0],
                ];
                return response()->json($result,400);
            }
        }
        return parent::render($request, $e);
    }
}
